from rest_framework import serializers
from .models import User

class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    
    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'avatar', 'user_type', 'date_joined']
        extra_kwargs = {
            'password': {'write_only': True},
            'user_type': {'read_only': True},  # 注册时默认为普通用户
        }
    
    def create(self, validated_data):
        """创建用户，默认设置为普通用户"""
        user = User(**validated_data)
        user.set_password(validated_data['password'])
        user.user_type = 'user'  # 注册时默认为普通用户
        user.save()
        return user

class LoginSerializer(serializers.Serializer):
    """登录序列化器"""
    username = serializers.CharField()
    password = serializers.CharField()